#include <iostream>
#include <vector>

using namespace std;

#include "cgal_helper.h"
#include "GreedyTriangulation.h"

GreedyTriangulation::GreedyTriangulation(vector<Point> p_list): p_list(p_list) {}

CGALTriangulation &GreedyTriangulation::get_triangulation() {
  return _t;
}

void GreedyTriangulation::run() {
  int begin = 4;
  random_shuffle(p_list.begin(), p_list.end());
  _t.insert(p_list.begin(), p_list.begin()+begin);
  vector<Point> p_temp(p_list.begin()+begin, p_list.end());

  while (p_temp.size()) {
    cout << "Temp Size: " << p_temp.size() << endl;
    CGALTriangulation::Locate_type lt;
    int li;
    int lj;
    int closest_p = -1;
    FT dist = -1.0;
    CGALTriangulation::Facet f;
   
    for (CGALTriangulation::Finite_facets_iterator it = _t.finite_facets_begin(); it != _t.finite_facets_end(); it++) {
      for (unsigned int j = 0; j < p_temp.size(); j++) {
        FT dist_1 = Segment(it->first->vertex((it->second+1)&3)->point(), p_temp [j]).squared_length();
        FT dist_2 = Segment(it->first->vertex((it->second+2)&3)->point(), p_temp [j]).squared_length();
        FT dist_3 = Segment(it->first->vertex((it->second+3)&3)->point(), p_temp [j]).squared_length();

        if ((dist_1+dist_2+dist_3) > dist) {
          dist  = dist_1 + dist_2 + dist_3;
          closest_p = j;
          f     = *it;
        }
      }
    }
    _t.insert(p_temp [closest_p]);
    p_temp.erase(p_temp.begin()+closest_p);
  }
  //_t.locate(closest_p, lt, li, lj, CGALTriangulation::Cell_handle());

  cout << _t.number_of_cells() << endl;
}
